<template>
  <div class="container">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" type="circle" :percentage="100" class="progress" />
    </el-upload>
  </div>
</template>

<script>

// 将操作对象存储的 SDK 插件导入到项目中
const COS = require('cos-js-sdk-v5')
// 实例化 COS ，传入 SecretId 以及 SecretKey
var cos = new COS({
  SecretId: 'AKIDDNHuGK8etsa1C7k6BzXnmUw83h5C3ey1',
  SecretKey: 'nJYXFgqjLgkW3JmyuZx3xaw1oLbZGgqj'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      percentage: 0, // 图片上传进度
      showProgress: false
    }
  },
  methods: {
    // 自定义上传行为
    upload(file) {
      this.showProgress = true
      //   console.log(file.file)
      if (file.file) {
        cos.putObject({
          Bucket: 'first-1307084519', /* 必须,存储桶名称 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: 'file.file.name', /* 文件名，必须 */
          StorageClass: 'STANDARD',
          Body: file.file, // 上传文件对象
          onProgress: (progressData) => {
            // console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
          }
        }, (err, data) => {
        //   console.log(err || data)
          if (err === null && data.statusCode === 200) {
            this.imageUrl = `https:${data.Location}`
            this.showProgress = false
          }
        })
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style>
 .progress {
    position: absolute;
    display: flex;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #e4e4e4;
    border-radius: 50%;
    opacity: 0.9;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
